﻿Imports VendasBLL
Imports VendasDAL
Imports ModuloEstoque
Imports EstoqueBLL
Public Class AgendamentoFRM
    Dim ObjBLL As New AgendamentoBLL
    Dim ObjServico As New ServicoBLL
    Dim ObjPlaca As New PlacaBLL
    Public Op As String
    Public Tipo As String
    Public CodPlaca As String
    Public CodServico As Integer
    Dim Custo As Decimal
    Dim Duracao As Date
    Public Codigo As Integer
    Dim tabitens As New DataTable

#Region "Carrega Propriedades"
    Public Sub carregaservico()
        If (Not IsNothing(ObjServico)) Then
            TXTServico.Text = ObjServico.pro_descricao
            CodServico = ObjServico.pro_codigo
            Custo = ObjServico.pro_precocusto
            Duracao = ObjServico.pro_duracao
        End If
    End Sub

    Public Sub carregaplaca()
        If (Not IsNothing(ObjServico)) Then
            TXTPlaca.Text = ObjPlaca.Descricao
            CodPlaca = ObjPlaca.Codigo
            TXTCliente.Text = ObjPlaca.CliDescricao
        End If
    End Sub
#End Region

#Region "Carrega Campos"
    Sub CarregaCampos(codigo As Integer)
        ObjBLL = New AgendamentoBLL(codigo)
        LBCodigo.Text = "Código: " & ObjBLL.Codigo
        TXTPlaca.Text = ObjBLL.DesPlaca
        CodPlaca = ObjBLL.CodPlaca
        TXTCliente.Text = ObjBLL.Cliente
        CBStatus.SelectedValue = ObjBLL.CodStatus
        TXTObs.Text = ObjBLL.Obs
        DTPData.Text = DateTime.Parse(ObjBLL.Data)
        DTPHora.Text = DateTime.Parse(ObjBLL.HrInicial)
        For Each item As ItensVendaBLL In ObjBLL.lVendas
            CodServico = item.ObjServico.pro_codigo
            TXTServico.Text = item.ObjServico.pro_descricao
            Custo = item.ObjServico.pro_precocusto
            Duracao = item.ObjServico.pro_duracao
            BAdicionar_Click(sender:="", e:=EventArgs.Empty)
        Next

    End Sub
#End Region

#Region "Busca Placa"
    Private Sub BBuscarPlaca_Click(sender As System.Object, e As System.EventArgs) Handles BBuscarPlaca.Click
        Dim ObjP As New ConsultaPlacasFRM
        ObjP.Tipo = "ret"
        ObjP.ShowDialog()
        If (Not IsNothing(ObjP.ObjP)) Then
            ObjPlaca = ObjP.ObjP
            carregaplaca()
        End If
    End Sub
#End Region

#Region "Busca Produto_Click"
    Private Sub BBuscarServico_Click(sender As System.Object, e As System.EventArgs) Handles BBuscarServico.Click
        Dim objpro As New ServicoCON
        objpro.tipo = "ret"
        objpro.ShowDialog()
        If (Not IsNothing(objpro.objprod)) Then
            ObjServico = objpro.objprod
            carregaservico()
        End If
    End Sub

#End Region

#Region "Lista"
    Sub Lista()
        tabitens = New DataTable()
        Try
            tabitens.Columns.Add("pro_codigo", GetType(Integer))
            tabitens.Columns.Add("pro_descricao", GetType(String))
            tabitens.Columns.Add("pro_precocusto", GetType(Decimal))
            tabitens.Columns.Add("pro_duracao", GetType(String))
            DGVDados.DataSource = tabitens
        Catch
        End Try

    End Sub
#End Region

#Region "Valida Item"
    Function validaItem() As Boolean
        Dim ret As Boolean
        ret = False
        For Each linha As DataRow In tabitens.Rows
            If (linha("pro_codigo") = CodServico) Then
                ret = True
            End If
        Next
        Return ret
    End Function

#End Region

#Region "Carrega na Datagirdview"
    Sub Carrega_Selecao()
        Dim linha As DataRow
        linha = tabitens.NewRow
        linha("pro_codigo") = CodServico
        linha("pro_descricao") = TXTServico.Text
        linha("pro_precocusto") = Custo
        linha("pro_duracao") = FormatDateTime(Duracao, vbShortTime)
        tabitens.Rows.Add(linha)
        tabitens.AcceptChanges()
    End Sub

#End Region

#Region "Atualiza Valores tempo e custo"
    Sub AtualizaValores()

        Dim valor As Decimal
        Dim dt1 As TimeSpan = New TimeSpan(0, 0, 0)
        TXTTempo.Text = ""
        For Each col As DataGridViewRow In DGVDados.Rows
            valor = valor + col.Cells("pro_precocusto").Value
            Dim s As String = col.Cells("pro_duracao").Value.ToString
            Dim partes = s.Split(":"c)
            Dim horas As String = CStr(partes(0))
            Dim minutos As String = CStr(partes(1))
            Dim dt2 As TimeSpan = New TimeSpan(horas, minutos, 0)
            dt1 = dt1.Add(dt2)
            s = dt1.TotalHours
            partes = s.Split(","c)
            horas = CDec(partes(0))
            If (horas.Length = 1) Then
                horas = "0" & horas
            End If
            If (dt1.Minutes.ToString.Length = 1) Then
                TXTTempo.Text = horas.ToString & ":" & "0" & dt1.Minutes & ":00"
            Else
                TXTTempo.Text = horas.ToString & ":" & dt1.Minutes & ":00"
            End If


        Next
        TXTCusto.Text = valor
        TXTCusto.Text = FormatCurrency(TXTCusto.Text)
    End Sub
#End Region

#Region "Adicionar na Datagridview"
    Private Sub BAdicionar_Click(sender As System.Object, e As System.EventArgs) Handles BAdicionar.Click
        Try
            If TXTServico.Text <> "" Then
                If (Not validaItem()) Then
                    Carrega_Selecao()
                    AtualizaValores()
                Else : Throw New Exception("Serviço já inserido.")
                End If
            Else : Throw New Exception("Insira um serviço válido")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Finally
            TXTServico.Text = ""
            Custo = Nothing
            Duracao = Nothing
            CodServico = Nothing
        End Try

    End Sub
#End Region

#Region "Cor de fundo do datagridview"
    Private Sub DGVDados_RowPrePaint(sender As System.Object, e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles DGVDados.RowPrePaint
        If DGVDados.Rows(e.RowIndex).Index Mod (2) = 1 Then
            DGVDados.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Gainsboro
        End If
    End Sub
#End Region

#Region "Load do Formulário"
    Private Sub AgendamentoFRM_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Limpa()
        Lista()
        objconexao.carregaCombo(CBStatus, "Generico.Gen_Status", "sta_codigo", "sta_descricao", "sta_codigo < 3", "sta_codigo")
        If (Op = "I") Then
            LBCodigo.Visible = False
            LBTitulo.Text = "Agendamento"
            LBCodigo.Text = 0

        Else
            LBCodigo.Visible = True
            CarregaCampos(Codigo)
        End If
    End Sub

#End Region

#Region "Remover da Datagridview"
    Private Sub BExcluir_Click(sender As System.Object, e As System.EventArgs) Handles BExcluir.Click
        Try
            Dim indice As Integer
            indice = -1

            For Each linha As DataGridViewRow In DGVDados.SelectedRows
                If (Not linha.Cells("pro_codigo") Is Nothing) Then
                    indice = linha.Index
                End If
            Next
            If (indice <> -1) Then
                tabitens.Rows.RemoveAt(indice)
                tabitens.AcceptChanges()
                AtualizaValores()
            Else : Throw New Exception("Selecione um serviço para remover")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub

#End Region

#Region "Voltar"
    Private Sub TSBVoltar_Click(sender As System.Object, e As System.EventArgs) Handles TSBVoltar.Click
        Me.Close()
    End Sub
#End Region

#Region "Salvar/Alterar"
    Private Sub TSBSalvar_Click(sender As System.Object, e As System.EventArgs) Handles TSBSalvar.Click

        Try

            ObjBLL = New AgendamentoBLL(Codigo, DTPData.Text, FormatDateTime(DTPHora.Value, vbShortTime), StrConv(Trim(TXTObs.Text), VbStrConv.ProperCase), CBStatus.SelectedValue, CodPlaca)
            Dim obj As ItensVendaBLL
            For Each linha As DataRow In tabitens.Rows
                obj = New ItensVendaBLL
                obj.IteCodigo = ObjBLL.Codigo
                obj.ObjServico = New ServicoBLL(linha("pro_Codigo").ToString)
                ObjBLL.lVendas.Add(obj)
            Next
            If Op = "I" Then
                ObjBLL.Inserir()
                MessageBox.Show("Agendamento inserido com sucesso", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Limpa()
                Me.Close()
            Else
                ObjBLL.Alterar()
                MessageBox.Show("Agendamento alterado com sucesso", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Limpa()
                Me.Close()
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub
#End Region

#Region "Limpar campos"
    Sub Limpa()
        CBStatus.SelectedValue = 1
        TXTObs.Text = ""
        TXTTempo.Text = "00:00:00"
        TXTCusto.Text = FormatCurrency("0")
        ' DGVDados.DataSource = Nothing
        CodPlaca = 0
        TXTServico_TextChanged(sender:="", e:=EventArgs.Empty)
        TXTPlaca.Text = ""
        TXTCliente.Text = ""
        TXTPlaca.Text = ""
        Me.ObjBLL = Nothing
    End Sub
#End Region

#Region "TXTServiço"
    Private Sub TXTServico_TextChanged(sender As System.Object, e As System.EventArgs) Handles TXTServico.TextChanged
        If TXTServico.Text <> "" Then
            BAdicionar.Enabled = True
        Else
            BAdicionar.Enabled = False
        End If
    End Sub
#End Region


    Private Sub AgendamentoFRM_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If (e.KeyCode = Keys.Escape) Then
            Me.Close()
        End If
    End Sub
End Class